<template>
  <div id="topRef">
    <h1 style="text-align: center;">试卷刷题</h1>
  </div>
  <el-divider />
  <div class="body">
    
    <div class="answerPaper" v-show="state.answerPaperVisible">
      <div class="submitandcancelButton">
        <el-button type="success" @click="submitAnswerPaperClick">提交</el-button>
        <el-button type="primary" v-show="state.viewAnswerResultButtonVisible" @click="viewAnswerResultClick">查看结果</el-button>
        <el-button type="danger" @click="returnHomePageClick">返回</el-button>
      </div>
      <!-- 走马灯显示试题作答  -->
     
      <el-carousel
       indicator-position="outside"
       :interval="6000"       
        arrow="always"
         height="700px"
         >
        <el-carousel-item v-for="(item,index) in state.questionsList" :key="item">
          <el-text type="warning">第{{ index+1 }}题</el-text>
          <div v-html="item.content_front_no_option" class="line-break" />
          <el-image v-for="url in item.images" :key="url" :src="url" style="width: 400px;" />
          <div class="option_list">
            <el-radio-group v-model="state.userAnswerList[index].userWrite" @change="optionChange(index)">
              <el-radio v-for="(option,option_index) in item.option_list" :label="option[0]" :key="option_index" >                
                <div v-html="option" class="line-break" />
              </el-radio>
      
            </el-radio-group>
          </div>
        </el-carousel-item>
      </el-carousel>
      <h4 style="text-align: center;">{{ state.paper.title }}</h4>
    </div>
    <div class="myInformation" ref="myInformationRef" v-show="state.myInformationVisible">        
        <p>刷卷数量：<el-text type="warning" size="large">{{ state.user_info.do_paper_count }}</el-text></p>
        <p>我的得分:<el-text type="success" size="large">{{ state.user_info.challenge_score }}</el-text></p>
        <p>总排名：<el-text type="primary" size="large">{{ state.myRanking }}</el-text></p>
        <p><el-button type="primary" size="small" @click="selectPaperClick">刷题</el-button></p>
        <h3>做题记录</h3>
        <el-table ref="paperOfUserListTableRef" class="tableClass" :data="state.paperOfUserList" stripe
            max-height="800"
            :row-style="{height:35+'px'}" 
            :cell-style="{padding:0+'px'}"
            :header-cell-style="{ background: '#eef1f6', color: '#606266' }"            
            border>                        
            <el-table-column type="index" width="60" label="序号" />
            <el-table-column width="55" property="score" label="分数" />
            <el-table-column width="70" property="accuracy_cn" label="准确率" />
            <el-table-column width="120" property="add_date" label="日期" />
            <el-table-column width="300" property="paper_info.title" label="试卷" />
        </el-table>
    </div>
    <div>
        <el-dialog
          v-model="state.dialogVisible"
          title="选择试卷"
          width="80%"
        >
            <div>（<el-text type="danger" size="large">红色</el-text>已做，<el-text type="success">绿色</el-text>未做）</div>
            <div>
              <span>选择学科</span>
              <el-radio-group v-model="state.subject" @change="subjectChange">
                <el-radio v-for="item of state.allSubject" :key="item.id" :label="item.id">{{item.name}}</el-radio>              
              </el-radio-group>
                            
            </div>
            <!-- 展示所有试卷 -->
            <div v-loading="state.loading">
              <el-button
                v-for="item in state.paperList"
                :key="item.name"
                :type="getButtonType(item.id)"
                text
                size="small"
                @click="getPaperClick(item.id)"
                >{{ item.title }}</el-button
              >
            </div>
            <template #footer>
                <span class="dialog-footer">
                <el-button @click="state.dialogVisible = false">取消</el-button>              
                </span>
            </template>
        </el-dialog>
        <!-- 查看作答结果 -->
        <el-dialog
          v-model="state.viewAnswerResultVisible"
          title="作答结果"
          width="80%"
        >
          <p>总分：<el-text size="large" type="primary">{{state.total_score}}</el-text></p>
          <el-carousel
            indicator-position="outside"
            :interval="6000"       
            arrow="always"
            height="720px"
          >
            <el-carousel-item v-for="(item,index) in state.questionsList" :key="item">           

              <div class="collectWrong">
                <el-text type="warning">第{{ index+1 }}题</el-text>
                <div v-if="isWrongQuestion(item)==false" >
                  <el-tooltip  class="box-item" effect="light" content="收藏错题" placement="top">
                    <el-button type="success" size="small"  :icon="Star" circle @click="onClickCollectWrong(item)" />
                  </el-tooltip>
                </div>
                <div v-if="isWrongQuestion(item)">
                  <el-tooltip  class="box-item" effect="dark" content="取消收藏" placement="top">
                    <el-button :icon="StarFilled" size="small" @click="onCancelWrongQuestion(item)" ></el-button>
                  </el-tooltip>
                </div>                
              </div>              
              <div v-html="item.content_front" class="line-break" justify="center"></div>
              <p><strong>参考答案：</strong></p>
              <div v-html="item.answer_front" class="line-break" justify="center"></div>
              <el-image v-for="url in item.images_answer" :key="url" :src="url" style="width: 200px;height: 260px;" />
              <p><strong>我的回答：</strong>
                <el-text size="large" 
                :type="selectColor(state.userAnswerList[index].score)"
                >{{ state.userAnswerList[index].userWrite }}
                </el-text>
              </p>
              <p><strong>解析：</strong></p>
              <div v-html="item.explain_front" class="line-break" justify="center"></div>
              <el-image v-for="url in item.images_expalain" :key="url" :src="url" style="width: 200px;height: 220px;" />
            </el-carousel-item>
          </el-carousel>
        </el-dialog>
    </div>
    <div class="table">
        <h3 style="text-align: center;">排行榜</h3>
        <el-table ref="multipleTableRef" class="tableClass" :data="state.rankingData" stripe
            max-height="800"
            :row-style="{height:35+'px'}" 
            :cell-style="{padding:0+'px'}"
            :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
            align="center"
            border>                        
            <el-table-column type="index" width="60" label="名次" />
            <el-table-column width="55" property="challenge_score" label="分数" />
            <el-table-column width="100" property="nickname" label="挑战者" />                            
        </el-table>
        <el-pagination
            background
            layout="total, pre, pager, next"
            :total="state.total"                
            :page-size="state.pageSize"            
            @current-change="handleCurrentChange"
        />
    </div>
  </div>
</template>
  
<script setup>
import {reactive, onMounted} from 'vue'
import { localGet, deepClone, verifyToken} from '@/utils'
import { ElMessage } from 'element-plus'
import axios from '@/utils/axios'
import { Star } from '@element-plus/icons-vue'

const state = reactive({
    total_score:0,
    loading:true,
    userAnswerList:[],
    currentQuestionIndex:1,
    range:'all',
    paperOfUserList:[],
    paperOfUserIdList:[],
    questionsList:[],
    allSubject:[],
    subject:1,
    paper:{},
    paperID:0,
    myRanking:0,
    dialogVisible:false,
    myInformationVisible:true,
    answerPaperVisible:false,
    viewAnswerResultButtonVisible:false,
    viewAnswerResultVisible:false,
    content: '',
    rankingData:[],
    total: 0, // 总条数
    currentPage: 1, // 当前页
    pageSize: 20, // 分页大小
    user_info:Object,
    userWrongQuestions:[],
    userWrongQuestions_id:[],
})
// 点击收藏错题
const onClickCollectWrong=(item)=>{
    let params={ question_id: item.id}
    console.log('我要发送收集错题')
    axios.post(`/questions/create_wrong_question/`, params).then(res => {
      if (res.code==200){
        ElMessage.success("收藏错题成功！")
        state.userWrongQuestions = res.data.results
        state.userWrongQuestions_id=state.userWrongQuestions.map(item=>item.question_info.id)
      }else
      if(res.code==1022){
        ElMessage("该题已经被收藏，没必要重复添加") 
      }
      else{
        ElMessage("收藏错题失败")       
      }
    })
    .catch((error)=>{
      console.log("收藏错误", error)
    })   
  }

  // 该题目是否被收藏
  const isWrongQuestion=(item)=>{
    let flag = false
    for(let question of state.userWrongQuestions_id){
      if (question.id == item.id){
        flag = true
        break
      }
    }
    return flag
  }
  // 获取该用户所有收藏的题目, 不分页的所有题目
  const getAllWrongQuestions=()=>{
    axios.get(`/questions/get_wrong_for_owner/`).then(res => {
      console.log("该用户的所有错题：",res)
      if (res.code==200){
        state.userWrongQuestions = res.data.results
        state.userWrongQuestions_id=state.userWrongQuestions.map(item=>item.question_info.id)
        console.log('错题id',state.userWrongQuestions_id)
      }else{
        ElMessage.error("获取你的错题失败")
      }
    })
    .catch((error)=>{
      console.log("获取收藏题目错误", error)
    })   
  }
// 取消收藏该题目
const onCancelWrongQuestion=(item)=>{
    let params={ question_id: item.id}
    axios.delete(`/UserWrongQuestionAPIView?question_id=`+item.id).then(res => {
      if (res.code==200){
        ElMessage.success("取消收藏成功！")
        state.userWrongQuestions = res.data.results
      }else{
        ElMessage.error("取消收藏失败")
        if (res.code==403){
          ElMessage.warning("请重新登录")
          // router.push("/login")
        }
      }
    })
    .catch((error)=>{
      console.log("取消收藏错误", error)
    })   
  }

// 用户筛选不同的颜色,分别是绿色与红色
const buttonTypeList = ['primary','danger']
// 查看答题结果
const viewAnswerResultClick=()=>{
  console.log('查看答题结果：',state.userAnswerList)
  state.viewAnswerResultVisible=true
}
// 根据用户的回答和参考答案，显示按钮不同的颜色
const selectColor=(score)=>{
  if(score==1){
    return buttonTypeList[0]
  }else{
    return buttonTypeList[1]
  }
}
// 返回首页点击事件，初始化各个变量
const returnHomePageClick=()=>{
  state.answerPaperVisible=false;
  state.myInformationVisible=true;
  getRanking()
  getMyRanking()
  verifyToken()
  state.user_info=localGet("user_information")
}
//检测所有题目是否都作答,如果都作答，则统计总得分
const verifyHasAllWriten=()=>{
  let flag=true
  let total_score=0
  for(let item of state.userAnswerList){
    if(item.userWrite==''){
      flag=false
      break
    }else{
      total_score +=item.score
    }
  }
  state.total_score = total_score
  return [flag,total_score]
}
//提交试卷结果
const submitAnswerPaperClick=()=>{
  // 如果该试卷是曾经错过的，则不提交，并显示结果按钮，否则提交给后台，把本次作答数据持久化到数据库
  if(!state.paperOfUserIdList.includes(state.paper.id)){
    let [flag,total_score]=verifyHasAllWriten()
    // console.log("提交前用户所有作答：",state.userAnswerList)
    // console.log('作答标记：',flag)
    // console.log('得分：',total_score)
    if(flag==false){
      ElMessage.error('您还有题目未作答！')
      return false    
    }
    let accuracy=total_score/state.questionsList.length
    accuracy=accuracy.toFixed(2)
    let params={
      paper:state.paper.id,
      score:total_score,
      accuracy:accuracy,
      question_amount:state.userAnswerList.length,
    }
    axios.post(`/AnswerPaperOfUserModelViewSet/create_log/`,params).then(res => {
        console.log("提交结果：",res.data.results)
        if (res.code==200){ 
          state.viewAnswerResultButtonVisible=true
          ElMessage.success("恭喜提交成功，请点击查看结果")
        }else{  
          console.log("提交试卷失败",res)
          ElMessage.error('提交试卷失败')
        }
      })
      .catch((error)=>{
        console.log("错误：", error)
      })
  }else{
    let [flag,total_score]=verifyHasAllWriten()
    console.log("是否做完标记：",flag)
    if(flag==false){
      ElMessage.error('您还有题目未作答！')
      return false    
    }
    ElMessage.warning('您曾经做过本试卷，本次不计入总分')
    state.viewAnswerResultButtonVisible=true
  }
}
// 选项改编时，结算该题的得分，写入用户写题列表
const optionChange=(index)=>{
  // console.log("用户答题：",state.userAnswerList[index])
  if(state.questionsList[index].answer_front.includes(state.userAnswerList[index].userWrite)){
    state.userAnswerList[index].score = 1
  }else{
    state.userAnswerList[index].score = 0
  }
}
// 获取本人已经做过题目的列表id
const getChallengePaperOfUser=()=>{
    axios.get(`/AnswerPaperOfUserAPIView/`).then(res => {
      // console.log("已做试卷：",res.data.results)
      if (res.code==200){ 
          state.paperOfUserList=res.data.results        
          state.paperOfUserIdList = state.paperOfUserList.map(item=>item.paper)        
      }else{
        state.paperOfUserList=[]
        state.paperOfUserIdList=[]
        console.log("获取已做试卷错误失败：",res)
      }
    })
    .catch((error)=>{
      console.log("错误：", error)
    })
}
// 按钮颜色调整
  const getButtonType =(paperID)=>{
    // console.log("已做试卷id列表：", state.paperOfUserIdList)
    // console.log("当前试卷id", paperID)
    if(state.paperOfUserIdList.includes(paperID)){
      return buttonTypeList[1]
    }else{
      return buttonTypeList[0]
    }
    
  }
// 获取所有学科
const getAllSubject=()=>{
  axios.get(`/SubjectViewSet/`).then(res => {
      // console.log("所有学科：",res.data.results)
      if (res.code==200){        
        state.allSubject=res.data.results
      }else{
        console.log("获取学科失败：",res)
      }
    })
    .catch((error)=>{
      console.log("错误：", error)
    })
}
// 学科切换
const subjectChange=()=>{
  console.log('学科换了', state.subject)
  getAllPapersBySubject()
}
// 获取该学科下的所有试卷
const getAllPapersBySubject=()=>{
  let params = {
    subject_id:state.subject,
    range:state.range,
  }
  axios.get(`/PaperModelViewSet/subject`,{params}).then(res => {
      // console.log("获取所有试卷：",res)
      if (res.code==200){
        state.paperList = res.data.results
        state.loading=false
        ElMessage.success("获取所有试卷成功，请选择试卷")
      }else{
        state.paperList=[]
        console.log("获取所有试卷失败：",res)
      }
    })
    .catch((error)=>{
      console.log("错误：", error)
    })
}
// 获取试卷和相应的题目（选择题，除填空题以外）,如果获取成功，则关闭基本信息窗口，并开始答题
const getPaperClick=(id)=>{
  let params = {id:id}
  axios.get(`/PaperModelViewSet/${id}/`,{params}).then(res => {
      console.log("试卷题目：",res.data.results)
      if (res.code==200){
        state.paper= res.data.results
        state.questionsList = state.paper.questions.filter(item=>item.type == 1)
        // console.log('获得选择题',state.questionsList)
        // 初始化用户回答列表为题目的id
        state.userAnswerList=[]
        for(let item of state.questionsList){
          state.userAnswerList.push({id:item.id,userWrite:'',score:0})
        }
        // console.log('该试卷的题目列表',state.questionsList)
        state.dialogVisible=false
        state.myInformationVisible=false
        state.answerPaperVisible=true
        ElMessage.success("获取试卷成功，开始答题")
      }else{
        console.log("获取失败：",res)
      }
    })
    .catch((error)=>{
      console.log("错误：", error)
    })
}
// 滚到页面顶端
const scrollToTop=()=>{
    document.querySelector('#topRef').scrollIntoView(true);
}
const getRanking=()=>{
    let params={
        page: state.currentPage,
        size: state.pageSize,       
      }
    axios.get(`/UserModelViewSet/ranking/?ordering=-challenge_score`,{params}).then(res => {
      console.log("排名榜：",res)
      if (res.code==200){
        // console.log("导学案列表：",res.data.results)
        state.rankingData = res.data.results
        state.total=res.total   
        scrollToTop()
      }else{   
        console.log("获取失败：",res)
        
      }
    })
    .catch((error)=>{
      console.log("错误：", error)
    })
}
// 获取我的排名
const getMyRanking=()=>{
    axios.get("/UserModelViewSet/my_ranking/").then(res => {
      if (res.code==200){
        // console.log("导学案列表：",res.data.results)
        state.myRanking = res.data.results    
      }else{   
        console.log("获取失败：",res)       
      }
    })
    .catch((error)=>{
      console.log("错误：", error)
    })
}
onMounted(()=>{
    state.currentPage = 1
    getRanking()
    getMyRanking()
    verifyToken()
    state.user_info=localGet("user_information")
    getAllSubject()
    getChallengePaperOfUser()
    getAllWrongQuestions()
})
// 选择试卷按钮后，获取该试卷的题目
const selectPaperClick=()=>{
  // console.log("打开弹窗，并获取所有信息技术的试卷")
  state.dialogVisible=true
  getAllPapersBySubject()
}
//点击页码时触发
const handleCurrentChange = (newPage)=>{
    state.currentPage = newPage 
    getRanking()
}

</script>
<style scoped>
  .body{
    display: flex;
    flex-flow: row nowrap;
    align-items: flex-start;
    justify-content: space-evenly;
    overflow-y: auto;
    margin:0;
    padding:0;
    width: 900px;
  }
  .myInformation{
    padding: 3px;
    width: 68%;
    border-style: solid;
    border-color: darkgreen;
    border-radius: 10px;
  }
  .table{
    display: flex;
    flex-flow: column nowrap;
    align-items: center;
    padding: 0px 3px 0 3px;
    width: 30%;
  }
  .answerPaper{
    padding: 3px;
    width: 68%;
    border-style: solid;
    border-color: darkgreen;
    border-radius: 20px;
  }
  .line-break{
  white-space: pre-wrap;
  font-size: 16px;
  }
  .el-carousel__item div {
  color: #475669;
  opacity: 0.75;
  margin: 0;
}
.el-carousel__item:nth-child(2n) {
  background-color: #f5fbf4;
}
.el-carousel__item:nth-child(2n + 1) {
  background-color: #fbfaf9;
}
.submitandcancelButton{
    display: flex;
    flex-flow: row nowrap;
    align-items: flex-start;
    justify-content: space-evenly;
}
.option_list{
  font-size: larger;
  font-weight: 300;
  display: flex;
  flex-flow: row nowrap;
  align-items: flex-start;
  justify-content:flex-start;
}
.collectWrong{
  display: flex;
  flex-flow: row nowrap;
  align-items: flex-start;
  justify-content: space-evenly
}
</style>